﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace WDTAsg2.DbBizObject
{
    public class FAQInfo
    {

        /// <summary>
        /// Gets the FAQ from the query string
        /// </summary>
        /// <param name="entry"></param>
        /// <returns></returns>
        public static SqlDataReader GetFAQResults(string entry)
        {

            String whereClause = "";
            // For loop splits the string, and then takes in word one by one,
            // every second word is a binary operator AND/OR (if not, fail)
            // and every other word is a key word
            // Dynamically consturctoing a SQL statement
            int i = 0;
            foreach (String part in entry.Split())
            {
                Console.WriteLine("Part: " + part);

                // Every second word
                if (i % 2 == 0)
                    whereClause = whereClause + String.Format(" (F.QuestionShort LIKE '%{0}%' OR F.QuestionLong LIKE '%{0}%' OR F.Answer LIKE '%{0}%') ", part);
                else
                {
                    if (part == "AND" || part == "OR")
                        whereClause = whereClause + part; // AND/OR 
                }
                i++;
            }


            // Escape characters,
            // Microsoft doesn't seem to believe in an  sql escape function anywhere on their MSDN
            whereClause.Replace("\'", "");
            whereClause.Replace(",", "");
            whereClause.Replace("(", "");
            whereClause.Replace(")", "");
            whereClause.Replace("[", "");
            whereClause.Replace("]", "");
            whereClause.Replace("<", "");
            whereClause.Replace(">", "");
            whereClause.Replace("\"", "");
            whereClause.Replace("\\", "");


            whereClause = "(" + whereClause + ")"; // Big brackets around it

            // Make connection
            string conString = ConfigurationManager.ConnectionStrings["HardwaresRUsCS"].ConnectionString;

            // Stored procedure is not possible here because it wont take an entire statement like this rather just a param,
            // and because of our AND + OR's it doesnt like them,
            // this seems to be the only option
            SqlConnection con = new SqlConnection(conString);
            SqlCommand cmd = new SqlCommand(String.Format("SELECT * FROM Faq F WHERE {0}", whereClause), con);

            con.Open();
            SqlDataReader dtr = cmd.ExecuteReader();
            return dtr;


        }


    }
}